<?php

namespace App\Api\Controllers;

use App\Api\Requests\CreateRegionAPIRequest;
use App\Api\Requests\UpdateRegionAPIRequest;
use App\Models\Region;
use App\Repositories\RegionRepository;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Response;

/**
 * Class RegionController
 * @package App\Api\Controllers
 */

class RegionAPIController extends AppBaseController
{
    /** @var  RegionRepository */
    private $regionRepository;

    public function __construct(RegionRepository $regionRepo)
    {
        $this->regionRepository = $regionRepo;
    }

    /**
     * @param Request $request
     * @return Response
     *
     * @SWG\Get(
     *      path="/api/regions",
     *      summary="区域列表",
     *      tags={"Region"},
     *      description="获取所有区域",
     *      produces={"application/json"},
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  type="array",
     *                  @SWG\Items(ref="#/definitions/Region")
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function index(Request $request)
    {
        $regions = $this->regionRepository->all(
            $request->except(['skip', 'limit']),
            $request->get('skip'),
            $request->get('limit')
        );
        $regions = $regions->toArray();
        foreach ($regions as &$val) {
            $user = User::getSimpleUserBySotreId($val['id']);
            if ($user) {
                $val['user'] = $user->toArray();
            }
        }
        return $this->sendResponse($regions);
    }

    /**
     * @param CreateRegionAPIRequest $request
     * @return Response
     *
     * @SWG\Post(
     *      path="/regions",
     *      summary="添加区域",
     *      tags={"Region"},
     *      description="Store Region",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="body",
     *          in="body",
     *          description="Region that should be stored",
     *          required=false,
     *          @SWG\Schema(ref="#/definitions/Region")
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  ref="#/definitions/Region"
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function store(CreateRegionAPIRequest $request)
    {
        DB::beginTransaction();
        try{
            $input = $request->all();
            $model = Region::where('name',$input['name'])->first();
            if($model){
                uexception('区域名已存在');
            }
            $input['password'] = Hash::make($input['password']);
            $region = $this->regionRepository->create($input);
            $input['region_id'] = $region['parent_id'];
            $input['store_id'] = $region['id'];
            User::createUser($input);
            DB::commit();
            return $this->sendResponse($region->toArray());
        }catch (\Exception $e){
            DB::rollBack();
            return $this->sendError($e->getMessage());
        }

    }

    /**
     * @param int $id
     * @return Response
     *
     * @SWG\Get(
     *      path="/regions/{id}",
     *      summary="Display the specified Region",
     *      tags={"Region"},
     *      description="Get Region",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="id",
     *          description="id of Region",
     *          type="integer",
     *          required=true,
     *          in="path"
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  ref="#/definitions/Region"
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function show($id)
    {
        /** @var Region $region */
        $region = $this->regionRepository->find($id);

        if (empty($region)) {
            return $this->sendError('Region not found');
        }

        return $this->sendResponse($region->toArray(), 'Region retrieved successfully');
    }

    /**
     * @param int $id
     * @param UpdateRegionAPIRequest $request
     * @return Response
     *
     * @SWG\Put(
     *      path="/regions/{id}",
     *      summary="Update the specified Region in storage",
     *      tags={"Region"},
     *      description="Update Region",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="id",
     *          description="id of Region",
     *          type="integer",
     *          required=true,
     *          in="path"
     *      ),
     *      @SWG\Parameter(
     *          name="body",
     *          in="body",
     *          description="Region that should be updated",
     *          required=false,
     *          @SWG\Schema(ref="#/definitions/Region")
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  ref="#/definitions/Region"
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function update($id, UpdateRegionAPIRequest $request)
    {
        DB::beginTransaction();
        try{
            $input = $request->all();
            /** @var Region $region */
            $region = $this->regionRepository->find($id);

            if (empty($region)) {
                return $this->sendError('Region not found');
            }
            $region = $this->regionRepository->update($input, $id);
            if(!isset($input['user_id'])){
                uexception('user_id必须传');
            }
            User::updateUser($input['user_id'], $input);
            DB::commit();
            return $this->sendResponse($region->toArray());
        }catch (\Exception $e){
            DB::rollBack();
            return $this->sendError($e->getMessage());
        }
    }

    /**
     * @param int $id
     * @return Response
     *
     * @SWG\Delete(
     *      path="/regions/{id}",
     *      summary="Remove the specified Region from storage",
     *      tags={"Region"},
     *      description="Delete Region",
     *      produces={"application/json"},
     *      @SWG\Parameter(
     *          name="id",
     *          description="id of Region",
     *          type="integer",
     *          required=true,
     *          in="path"
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="successful operation",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(
     *                  property="success",
     *                  type="boolean"
     *              ),
     *              @SWG\Property(
     *                  property="data",
     *                  type="string"
     *              ),
     *              @SWG\Property(
     *                  property="message",
     *                  type="string"
     *              )
     *          )
     *      )
     * )
     */
    public function destroy($id)
    {
        /** @var Region $region */
        $region = $this->regionRepository->find($id);

        if (empty($region)) {
            return $this->sendError('Region not found');
        }

        $region->delete();

        return $this->sendResponse($id, '操作成功');
    }
}
